/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.mybatis.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import java.util.List;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.schema.Column;
import org.elsfs.cloud.common.mybatis.properties.MybatisPlusProperties;
import org.elsfs.cloud.tenant.api.handler.TenantHandler;

/**
 * 租户配置
 *
 * @author zeng
 */
@RequiredArgsConstructor
public class TenantLineHandlerImpl implements TenantLineHandler, TenantHandler<Column> {

  private final MybatisPlusProperties mybatisPlusProperties;

  @Override
  public Expression getTenantId() {
    // 获取当前租户信息
    return new StringValue(findTenantId());
  }

  @Override
  public String getTenantIdColumn() {
    // 如果该字段你不是固定的，请使用 SqlInjectionUtils.check 检查安全性
    return mybatisPlusProperties.getTenant().getTenantIdColumn();
  }

  /**
   * 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
   *
   * @param tableName 表名
   * @return 是否忽略, true:表示忽略，false:需要解析并拼接多租户条件
   */
  @Override
  public boolean ignoreTable(String tableName) {
    return mybatisPlusProperties.getTenant().getIgnoreTable().contains(tableName);
  }

  @Override
  public boolean ignoreInsertAndUpdate(List<Column> columns, String tenantIdColumn) {
    return columns.stream()
        .map(Column::getColumnName)
        .anyMatch(i -> i.equalsIgnoreCase(tenantIdColumn));
  }
}
